/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jmail;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

/**
 *
 * @author WangShuai
 */
public class ReviceMail {

    /**
     * 获取邮件收件人，抄送，密送的地址和信息。根据所传递的参数不同 "to"-->收件人,"cc"-->抄送人地址,"bcc"-->密送地址
     * @param type
     * @param msg
     * @return
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public static String getToAddress(Message msg, String type) throws MessagingException, UnsupportedEncodingException {
        String mailaddr = "";
        String addrType = type.toUpperCase();
        InternetAddress[] address = null;

        if (addrType.equals("TO") || addrType.equals("CC") || addrType.equals("BCC")) {
            if (addrType.equals("TO")) {
                address = (InternetAddress[]) msg.getRecipients(Message.RecipientType.TO);
            }
            if (addrType.equals("CC")) {
                address = (InternetAddress[]) msg.getRecipients(Message.RecipientType.CC);
            }
            if (addrType.equals("BCC")) {
                address = (InternetAddress[]) msg.getRecipients(Message.RecipientType.BCC);
            }

            if (address != null) {
                for (int i = 0; i < address.length; i++) {
                    String mail = address[i].getAddress();
                    if (mail == null) {
                        mail = "";
                    } else {
                        mail = MimeUtility.decodeText(mail);
                    }
                    String personal = address[i].getPersonal();
                    if (personal == null) {
                        personal = "";
                    } else {
                        personal = MimeUtility.decodeText(personal);
                    }
                    String compositeto = personal + "<" + mail + ">";
                    mailaddr += "," + compositeto;
                }
                mailaddr = mailaddr.substring(1);
            }
        } else {
            throw new RuntimeException("Error email Type!");
        }
        return mailaddr;
    }

    /**
     * 获取发送邮件者信息
     * @return
     * @throws MessagingException
     */
    public static String getFromAddress(Message msg) throws MessagingException {
        InternetAddress[] address = (InternetAddress[]) msg.getFrom();
        String from = address[0].getAddress();
        if (from == null) {
            from = "";
        }
        String personal = address[0].getPersonal();
        if (personal == null) {
            personal = "";
        }
        String fromaddr = personal + "<" + from + ">";
        return fromaddr;
    }

    /**
     * 获取邮件主题
     * @return
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     */
    public static String getSubject(Message msg) throws UnsupportedEncodingException, MessagingException {
        String subject = "";
        subject = MimeUtility.decodeText(msg.getSubject());
        if (subject == null) {
            subject = "";
        }
        return subject;
    }

    /**
     * 获取邮件发送日期
     * @return
     * @throws MessagingException
     */
    public static String getSendDate(Message msg) throws MessagingException {
        Date sendDate = msg.getSentDate();
        SimpleDateFormat smd = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return smd.format(sendDate);
    }

    /**
     * 判断邮件是否需要回执，如需回执返回true，否则返回false
     * @return
     * @throws MessagingException
     */
    public static boolean getReplySign(Message msg) throws MessagingException {
        boolean replySign = false;
        String needreply[] = msg.getHeader("Disposition-Notification-TO");
        if (needreply != null) {
            replySign = true;
        }
        return replySign;
    }

    /**
     * 获取此邮件的message-id
     * @return
     * @throws MessagingException
     */
    public static String getMessageId(MimeMessage msg) throws MessagingException {
        return msg.getMessageID();
    }

    /**
     * 判断此邮件是否已读，如果未读则返回false，已读返回true
     * @return
     * @throws MessagingException
     */
    public static boolean isRead(Message msg) throws MessagingException {
        boolean isnew = false;
        Flags flags = ((Message) msg).getFlags();
        Flags.Flag[] flag = flags.getSystemFlags();
        System.out.println("flags's length:" + flag.length);
        for (int i = 0; i < flag.length; i++) {
            if (flag[i] == Flags.Flag.SEEN) {
                isnew = true;
                System.out.println("seen message .......");
                break;
            }
        }

        return isnew;
    }

    /**
     * 解析邮件，解析邮件 主要根据MimeType的不同执行不同的操作，一步一步的解析
     * @param part
     * @throws MessagingException
     * @throws IOException
     */
    public static void getMailContent(Part part, StringBuilder bodytext) throws MessagingException, IOException {
        String contentType = part.getContentType();
        int nameindex = contentType.indexOf("name");
        boolean conname = false;
        if (nameindex != -1) {
            conname = true;
        }
        //System.out.println("CONTENTTYPE:" + contentType);
        if (part.isMimeType("text/plain") && !conname && bodytext.length() < 1) {
            bodytext.append((String) part.getContent());
        } else if (part.isMimeType("text/html") && !conname && bodytext.length() < 1) {
            bodytext.append((String) part.getContent());
        } else if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();
            int count = multipart.getCount();
            for (int i = 0; i < count; i++) {
                getMailContent(multipart.getBodyPart(i), bodytext);
            }
        } else if (part.isMimeType("message/rfc822")) {
            getMailContent((Part) part.getContent(), bodytext);
        }
    }

    public static void main(String[] args) {
        String protocal = "pop3";
        String host = "mail.hengzhi.cc";
        int port = 110;
        String username = "gobbler";
        String password = "hengzhi";
        Store store = null;
        Folder folder = null;
        try {
            Properties props = System.getProperties();
            props.put("mail.debug", "true");
            props.put("mail.store.protocol", protocal);
            props.put("mail.host", host);
            props.put("mail.user", username);
            props.put("mail.password", password);
            Session session = Session.getDefaultInstance(props);
            //Session session = Session.getInstance(props, null);
            //URLName urln = new URLName(protocal, host, port, null, username, password);
            //store = session.getStore(urln);
            store = session.getStore();
            store.connect(username,password);
            folder = store.getFolder("INBOX");
            //folder.open(Folder.READ_ONLY);
            folder.open(Folder.READ_WRITE);
            //Get message count
            int mCount = folder.getMessageCount();
            System.out.println("Count: " + mCount);
            //Get the special number message  650  700 1114
            //Get the  test email
//            MimeMessage tMsg = (MimeMessage) folder.getMessage(1431);
//            System.out.println("Subject: " + getSubject(tMsg));
//            System.out.println("From: " + getFromAddress(tMsg));
//            StringBuilder builder = new StringBuilder();
//            getMailContent(tMsg, builder);
            //System.out.println(builder);
            //           System.out.println("To: " + getToAddress(tMsg, "TO"));
            //            System.out.println("Date: " + getSendDate(tMsg));
            //            System.out.println("ID: " + getMessageId(tMsg));
            //            System.out.println("ReplySign: " + getReplySign(tMsg));
            //            System.out.println("Read: " + isRead(tMsg));
            //            tMsg.setFlag(Flags.Flag.SEEN, true);
                        //tMsg.setFlag(Flags.Flag.DELETED, true);
            //            System.out.println("Read: " + isRead(tMsg));
            //
            //            System.out.println("ContentType: " + tMsg.getContentType());

            //            StringBuilder builder = new StringBuilder();
            //            getMailContent(tMsg, builder);
            //            System.out.println("Content: " + builder.toString());
            //
            //            String content = builder.toString();

            //            Message message[] = folder.getMessages();
            //            for (int i = 0, n = message.length; i < n; i++) {
            //                System.out.println(i + ": " + message[i].getFrom()[0] + "  " + message[i].getSubject());
            //            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (folder != null) {
                    folder.close(true);
                }
                if (store != null) {
                    store.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
